﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;
using CompanyBussiness;

namespace Website.admin.Control
{
    public partial class cCreateProduct : System.Web.UI.UserControl
    {
        NewsManagement newsMana = new NewsManagement();
        ProductManagement proMana = new ProductManagement();
        LanguagesManagement languageMana = new LanguagesManagement();
        CompanyBussiness.TypeProduct typeProduct;
        CompanyBussiness.TypeProperty typeProperty;
        CompanyBussiness.Language language;
        CompanyBussiness.Product product;
        CheckValid cv = new CheckValid();
        string strFileName = "";
        bool AddOrUp = false;
        int STRproductID;
        string error = "";
        string modulCode;
        bool ImgStatus = true;
        int idPropertyOut;

        protected void Page_Load(object sender, EventArgs e)
        {
            modulCode = Request.QueryString["Mod"];

            //bdProductDateIn.SelectedDate = DateTime.Now;
            if (Request.Cookies[CONST.COOKIES_LANGUAGE] == null)
            {
                Session[CONST.SESSION_LANGUAGE] = "";
                language = languageMana.GetLanguageByCode("vi-VN");
            }
            else
            {
                Session[CONST.SESSION_LANGUAGE] = Request.Cookies[CONST.COOKIES_LANGUAGE][CONST.COOKIES_LANGUAGE_ID];
                language = languageMana.GetLanguageByID(int.Parse(Session[CONST.SESSION_LANGUAGE].ToString()));
            }
            this.LoadDropParentCategory();

            if (Request[CONST.QUERYSTRING_PRODUCT] == null || Request.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_TYPE] == "AddProduct")
            {
                AddOrUp = false;
                btnDelete.Visible = false;
                //linkBack.Visible = false;
                lbTypeAction.Text = "Thêm mới sản phẩm";
                dropChildCategory.Enabled = false;
                btnProperty.Visible = false;
            }
            else
            {
                AddOrUp = true;
                STRproductID = int.Parse(Request[CONST.QUERYSTRING_PRODUCT]);
                this.LoadForm();
                dropChildCategory.Enabled = true;
                imgProductImg.Visible = true;
                lbTypeAction.Text = "Cập nhật sản phẩm";
                btnProperty.Visible = true;
            }

            fail.Visible = false;
            success.Visible = false;
        }

        protected void LoadDropParentCategory()
        {
            try
            {
                dropParentCategory.Items.Clear();
                //dropParentCategory.Items.Add("--- Danh mục cha ---");
                List<TypeProduct> listParentCategory = proMana.GetParentTypeProduct(language.LanguagesID, true);
                //foreach (var li in listParentCategory)
                //{
                //    dropParentCategory.Items.Add(li.TypeProductName);
                //}
                dropParentCategory.DataSource = proMana.GetParentTypeProduct(language.LanguagesID, true);
                dropParentCategory.DataTextField = "TypeProductName";
                dropParentCategory.DataValueField = "TypeProductID";
                dropParentCategory.DataBind();
                dropParentCategory.Items.Insert(0,new ListItem("--- Danh mục cha ---", "0"));
            }
            catch (Exception)
            {
                fail.Visible = true;
                lbError.Text = "Có lỗi trong khi load dữ liệu . Bạn hãy thử lại.";
            }
        }

        protected void LoadForm()
        {
            try
            {
                product = proMana.GetProductByID(STRproductID);
                txtProductName.Text = product.ProductName.ToString();

                if (product.ProductDes != null)
                    txtProductDes.Text = product.ProductDes.ToString();
                else
                    txtProductDes.Text = "";

                //if (product.ProductAuthor != null)
                //    txtProductAuthor.Text = product.ProductAuthor.ToString();
                //else
                //    txtProductAuthor.Text = "";

                if (product.Features != null)
                    txtFeatures.Value = product.Features.ToString();
                else
                    txtFeatures.Value = "";

                int TypeID = (int)product.TypeProductID;

                TypeProduct _typeProduct = proMana.GetTypeProductByID(TypeID);

                if (_typeProduct.ParentTypeProductID != null)
                {
                    TypeProduct ty = new TypeProduct();
                    ty = proMana.GetTypeProductByID((int)_typeProduct.ParentTypeProductID);
                    dropParentCategory.SelectedValue = ty.TypeProductID.ToString();
                    this.LoadDropChildCategory((int)_typeProduct.ParentTypeProductID);
                    dropChildCategory.SelectedValue = proMana.GetTypeProductByID(TypeID).TypeProductName.ToString();

                    
                }
                else
                {
                    dropParentCategory.SelectedValue = _typeProduct.TypeProductName;
                }

                if (product.ProductStatus == true)
                    checkStatus.Checked = true;
                else
                    checkStatus.Checked = false;

                //if (product.ProductQuantity != null)
                //    txtProductQuantity.Text = product.ProductQuantity.ToString();
                //else
                //    txtProductQuantity.Text = "";

                //if (product.ProductPrice != null)
                //    txtProductPrice.Text = product.ProductPrice.ToString();
                //else
                //    txtProductPrice.Text = "";

                //if (product.ProductDateIn != null)
                //    bdProductDateIn.SelectedDate = Convert.ToDateTime(product.ProductDateIn);
                //else
                //    bdProductDateIn.SelectedValue = null;

                //if (product.ProductSkin != null)
                //    txtProductSkin.Text = product.ProductSkin.ToString();
                //else
                //    txtProductSkin.Text = "";

                //if (product.ProductCode != null)
                //    lbProductCodes.Text = product.ProductCode.ToString();
                //else
                //{
                //    lbProductCode.Visible = false;
                //    lbProductCodes.Visible = false;
                //}



                if (product.ProductImg != null)
                    imgProductImg.ImageUrl = product.ProductImg.ToString();
                else
                    imgProductImg.ImageUrl = ConfigurationManager.AppSettings["NoImages"];


                if (product.ImagesStatus == true)
                {
                    checkImgStatus.Checked = true;
                }
                else
                    checkImgStatus.Checked = false;


                if (product.FileAttach != null)
                {
                    linkFileAttach.NavigateUrl = Server.MapPath(product.FileAttach);
                    linkFileAttach.Text = Path.GetFileName(Server.MapPath(product.FileAttach));
                }


                typeProperty = proMana.GetListTypePropertyByProductID(STRproductID)[0];
                if (typeProperty != null)
                {
                    btnProperty.Enabled = true;
                    Session[CONST.SESSION_TYPE_PROPERTY] = typeProperty.Id;
                    if (typeProperty.TypePropertiesName != null)
                    {
                        txtTypePropertiesName.Text = typeProperty.TypePropertiesName;
                    }

                    if (typeProperty.TypePropertiesDes != null)
                    {
                        txtTypePropertiesDes.Text = typeProperty.TypePropertiesDes;
                    }
                }
                else
                {
                    btnProperty.Enabled = false;
                }
                
            }
            catch (Exception)
            {
                //fail.Visible = true;
                //lbError.Text = "Có lỗi trong khi Load dữ liệu . Bạn hãy kiểm tra lại.";
            }

        }

        protected void LoadDropChildCategory(int parentTypeProductID)
        {
            try
            {
                dropChildCategory.Enabled = true;
                dropChildCategory.Items.Clear();

                List<TypeProduct> listChildCategory = proMana.GetChildrenTypeProductByParentID(parentTypeProductID, language.LanguagesID, true);
                if (listChildCategory.Count == 0)
                {
                    dropChildCategory.Enabled = false;
                }
                //foreach (var li in listChildCategory)
                //{
                //    dropChildCategory.Items.Add(li.TypeProductName);
                //}
                dropChildCategory.DataSource = proMana.GetChildrenTypeProductByParentID(parentTypeProductID, language.LanguagesID, true);
                dropChildCategory.DataTextField = "TypeProductName";
                dropChildCategory.DataValueField = "TypeProductID";
                dropChildCategory.DataBind();
             
            }
            catch (Exception)
            {
                //fail.Visible = true;
                //lbError.Text = "Có lỗi trong khi load dữ liệu . Bạn hãy thử lại.";
            }
        }

        protected void FormatForm()
        {
            try
            {
                if (AddOrUp == false)
                {
                    txtProductName.Text = "";
                    txtProductDes.Text = "";
                    //txtProductAuthor.Text = "";
                    txtFeatures.Value = "";
                    //txtProductPrice.Text = "";
                    //txtProductQuantity.Text = "";
                   // bdProductDateIn.SelectedValue = null;
                    //txtProductSkin.Text = "";
                    imgProductImg.ImageUrl = ConfigurationManager.AppSettings["NoImages"];
                    Session[CONST.SESSION_IMG] = null;
                    Session[CONST.SESSION_IMG_THUMBNAIL] = null;
                }
                else
                {
                    this.LoadForm();
                    Session[CONST.SESSION_IMG] = null;
                    Session[CONST.SESSION_IMG_THUMBNAIL] = null;
                }
            }
            catch (Exception)
            { }
        }

        protected bool GetData()
        {
            if (txtProductName.Text.Trim() != "")
            {
                product.ProductName = txtProductName.Text;
            }
            else
            {
                fail.Visible = true;
                lbError.Text = "Tên của sản phẩm bắt buộc phải có !";
                return false;
            }

            if (txtProductDes.Text.Trim() != "")
            {

                product.ProductDes = txtProductDes.Text;
                
            }
            else
            {
                product.ProductDes = "";
            }

            //if (txtProductAuthor.Text != "")
            //{
            //    product.ProductAuthor = txtProductAuthor.Text;
            //}
            //else
            //{
            //    product.ProductAuthor = "";
            //}

            if (txtFeatures.Value.ToString() != "")
            {

                product.Features = txtFeatures.Value.ToString();
            }
            else
            {
                product.Features = "";
            }

            if (checkStatus.Checked == true)
            {
                product.ProductStatus = true;
            }
            else
            {
                product.ProductStatus = false;
            }
            if (dropParentCategory.SelectedValue == "0")
            {
                fail.Visible = true;
                lbError.Text = "Bạn chưa chọn danh mục sản phẩm !";
                return false;
            }
            else
            {
                if (dropChildCategory.Items.Count == 0)
                {
                    //typeProduct = proMana.GetTypeProductByNameSingle(dropParentCategory.SelectedValue.ToString());
                    typeProduct=proMana.GetTypeProductByID(int.Parse(dropParentCategory.SelectedValue.ToString()));
                }
                else
                {
                    //typeProduct = proMana.GetTypeProductByNameSingle(dropChildCategory.SelectedValue.ToString());
                    typeProduct = proMana.GetTypeProductByID(int.Parse(dropChildCategory.SelectedValue.ToString()));
                }
            }

          
            if (Session[CONST.SESSION_IMG_THUMBNAIL] == null)
            {
                product.ProductImg = imgProductImg.ImageUrl.ToString();
            }
            else
            {
                product.ProductImg = ConfigurationManager.AppSettings["FolderImagesUpload"] + Session[CONST.SESSION_IMG_THUMBNAIL];
            }


            //if (txtProductPrice.Text.Trim() == "" || txtProductPrice.Text ==string.Empty || txtProductPrice.Text==null)
            //{

            //    product.ProductPrice = 0;
            //}
            //else
            //{
                
            //    if (cv.CheckNumber(txtProductPrice.Text))
            //    {
            //        product.ProductPrice = float.Parse(txtProductPrice.Text);
            //    }
            //    else
            //    {
            //        fail.Visible = true;
            //        lbError.Text = "Giá của sản phẩm không đúng định dạng !";
            //        return false;
            //    }
            //}

            //if (txtProductQuantity.Text.Trim() == "" || txtProductQuantity.Text==null || txtProductQuantity.Text==string.Empty)
            //{
            //    product.ProductQuantity = 0;     
            //}
            //else
            //{
                
            //    if (cv.CheckNumber(txtProductQuantity.Text))
            //    {
            //        product.ProductQuantity = Int32.Parse(txtProductQuantity.Text);
            //    }
            //    else
            //    {
            //        fail.Visible = true;
            //        lbError.Text = "Số lượng sản phẩm không đúng định dạng !";
            //        return false;
            //    }
            //}

            //if (txtProductSkin.Text.Trim() != "")
            //{
            //    product.ProductSkin = txtProductSkin.Text;
            //}
            //else
            //{
            //    product.ProductSkin = "Đang cập nhật...";
            //}

            //product.ProductDateIn = GetbdDate();

            if (checkImgStatus.Checked)
            {
                ImgStatus = true;
            }
            else
            {
                ImgStatus = false;
            }

            if (Session[CONST.SESSION_FILE_ATTACH] == null)
            {
                product.FileAttach = null;
            }
            else
                product.FileAttach = ConfigurationManager.AppSettings["FolderFileUpload"] + Session[CONST.SESSION_FILE_ATTACH];

            return true;
        }

        //private DateTime GetbdDate()
        //{

        //    string date = bdProductDateIn.SelectedDate.ToShortDateString();
        //    DateTime result = DateTime.Parse(date);
        //    return result;
        //}

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (AddOrUp == false)
                {
                    #region Addnew

                    modulCode = Request.QueryString["Mod"];

                    product = new Product();

                    if (GetData() == false)
                        return;

                    product.ProductDateIn = DateTime.Now;
                    product.ProductQuantity = 0;
                    product.ProductPrice = 0;

                    //tao san pham
                    int idOut= proMana.CreateProduct(product.ProductName,product.ProductDes,product.ProductAuthor,product.ProductSkin,(int)product.ProductQuantity,(float)product.ProductPrice,(DateTime)product.ProductDateIn,product.ProductImg,(bool)product.ProductStatus,ImgStatus,(int)typeProduct.TypeProductID,product.FileAttach,product.Features);

                    //tao thuoc tinh cho san pham vua tao
                    if(txtTypePropertiesName.Text!=string.Empty)
                    {
                        TypeProperty type=new TypeProperty();
                        type.ProductID=idOut;
                        type.TypePropertiesName=txtTypePropertiesName.Text;
                        type.TypePropertiesDes=txtTypePropertiesDes.Text;
                        idPropertyOut = proMana.CreateTypeProperty(type);

                        Session[CONST.SESSION_TYPE_PROPERTY] = idPropertyOut;
                    }
                    

                    //Tao metadata cho tin bai
                    Metadata meta = new Metadata();
                    meta.ProductID = idOut;
                    newsMana.CreateMetadata(meta);

                    //if (idPropertyOut == 0)
                    //{
                        //Cap nhat meta cho danh muc vua tao
                        Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "CreateMetadata";
                        Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_TYPE] = "CreateNew";
                        Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=CreateMetadata&Mod=" + modulCode + "&" + CONST.QUERYSTRING_PRODUCT + "=" + idOut);
                    //}
                    //else
                    //{ 
                    //    //chuyen sang trang tao cac thuoc tinh cu the cho san pham vua tao
                    //    Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "CreatProperty";
                    //    Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=CreatProperty&" + CONST.QUERYSTRING_TYPE_PROPERTY + "=" + idPropertyOut);
                    //}
                   
                    success.Visible = true;
                    lbSuccess.Text = "Bạn đã thêm mới sản phẩm thành công !";

                    dropParentCategory.SelectedIndex = 0;
                    dropChildCategory.Items.Clear();
                    dropChildCategory.Enabled = false;

                    this.FormatForm();

                    #endregion
                }
                else
                {
                    #region Update

                    product = proMana.GetProductByID(STRproductID);

                    if (GetData() == false)
                        return;

                    //kiêm tra thuoc tinh
                    typeProperty = proMana.GetListTypePropertyByProductID(STRproductID)[0];
                    if (typeProperty != null)
                    {
                        if (txtTypePropertiesName.Text != string.Empty)
                        {
                            typeProperty.TypePropertiesName = txtTypePropertiesName.Text;
                        }
                        else
                        {
                            fail.Visible = true;
                            lbError.Text = "Sản phẩm này có thuộc tính bạn không thể để trống tên của thuộc tính này";
                            return;
                        }

                        typeProperty.TypePropertiesDes = txtTypePropertiesDes.Text;

                        //cap nhat cho thuoc tinh
                        proMana.UpdateTypeProperty(typeProperty);

                        idPropertyOut = typeProperty.Id;
                        Session[CONST.SESSION_TYPE_PROPERTY] = idPropertyOut;
                    }
                    else
                    {
                        //tao thuoc tinh cho san pham can cap nhat
                        if (txtTypePropertiesName.Text != string.Empty)
                        {
                            TypeProperty type = new TypeProperty();
                            type.ProductID = product.ProductID;
                            type.TypePropertiesName = txtTypePropertiesName.Text;
                            type.TypePropertiesDes = txtTypePropertiesDes.Text;
                            idPropertyOut = proMana.CreateTypeProperty(type);
                            Session[CONST.SESSION_TYPE_PROPERTY] = idPropertyOut;
                        }


                    }

                    product.ProductQuantity = 0;
                    product.ProductPrice = 0;
      

                    proMana.UpdateProduct((int)product.ProductID, product.ProductName, product.ProductDes, product.ProductAuthor, product.ProductSkin, (int)product.ProductQuantity, (float)product.ProductPrice, (DateTime)product.ProductDateIn, product.ProductImg, (bool)product.ProductStatus,ImgStatus, (int)typeProduct.TypeProductID,product.FileAttach,product.Features);

                   

                    success.Visible = true;
                    lbSuccess.Text = "Bạn đã cập nhật sản phẩm thành công !";

                    this.LoadForm();

                    #endregion
                }
            }
            catch (Exception)
            {
                //fail.Visible = true;
                //lbError.Text = "Có lỗi trong khi sử lý dữ liệu . Bạn hãy kiểm tra lại.";
            }   
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            FormatForm();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                product = proMana.GetProductByID(STRproductID);
                proMana.DeleteProduct(product.ProductID);

                Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "ParentTypeProductDetail";
                Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=ParentTypeProductDetail");
            }
            catch (Exception)
            {
                fail.Visible = true;
                lbError.Text = "Có lỗi trong khi sử lý dữ liệu . Bạn hãy kiểm tra lại.";
            }
        }

        protected void dropParentCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropParentCategory.SelectedValue.ToString() != "0")
            {
                //typeProduct = proMana.GetTypeProductByNameSingle(dropParentCategory.SelectedValue.ToString());
                typeProduct=proMana.GetTypeProductByID(int.Parse(dropParentCategory.SelectedValue.ToString()));
                this.LoadDropChildCategory(typeProduct.TypeProductID);
            } 
        }

        protected void btnProperty_Click(object sender, EventArgs e)
        {

            //sang trang quan ly cac thuoc tinh con cua san pham
            Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "ListProperty";
            Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=ListProperty&" + CONST.QUERYSTRING_TYPE_PROPERTY + "=" + Session[CONST.SESSION_TYPE_PROPERTY].ToString());
        }

       
    }
}